package com.party.admin.web.controller.crowdfund;


import com.party.admin.biz.activity.ActivityBizService;
import com.party.admin.biz.asynexport.EventAsynExportService;
import com.party.admin.biz.crowdfund.ProjectBizService;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.crowdfund.*;
import com.party.core.model.notify.Event;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.ICrowfundFollowUpService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.order.IOrderFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/***
 * 众筹截止跟进
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "crowdfund/followUp")
public class CrowfundFollowUpController {

    @Autowired
    private ICrowfundFollowUpService crowfundFollowUpService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private EventAsynExportService eventAsynExportService;

    @Autowired
    private ActivityBizService activityBizService;

    protected static Logger logger = LoggerFactory.getLogger(CrowfundFollowUpController.class);


    /**
     * 众筹结束跟进初始化方法
     */
    @ResponseBody
    @RequestMapping(value = "initializationEventStatistics")
    public AjaxResult initializationEventStatistics() {
        /**初始化默认状态为处理完成*/
        int followState = 2;
        crowfundFollowUpService.initializationEventStatistics(followState);
        return AjaxResult.success();
    }


    /**
     * 众筹结束跟进列表
     *
     * @param crowdfundEvent 众筹事件
     * @param page           分页参数
     * @return 事件列表
     */
    @RequestMapping(value = "list")
    public ModelAndView endList(CrowdfundEventWithMemberPartner crowdfundEvent, Page page, CommonInput input) {

        try {
            page.setLimit(20);
            ModelAndView modelAndView = new ModelAndView("crowdfund/eventEndList");
            Map<String, Object> params = CommonInput.appendParams(input);
            crowdfundEvent.setIsMultiple(YesNoStatus.NO.getCode());
            List<Map<String, Object>> crowdfundEventList = crowfundFollowUpService.endList(crowdfundEvent, params, page);
            for (Map<String, Object> stringObjectMap : crowdfundEventList) {
                String eventId = stringObjectMap.get("eventId").toString();
                //剩余金额
                Double payMoney = orderFormService.findPaymentByEventId(eventId);
                stringObjectMap.put("remainMoney", BigDecimalUtils.round(payMoney, 2));
            }
            modelAndView.addObject("event", crowdfundEvent);
            modelAndView.addObject("list", crowdfundEventList);
            modelAndView.addObject("page", page);
            modelAndView.addObject("input", input);
            modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "eventEndFollow"));
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "endListExport")
    public AjaxResult endListExport(CrowdfundEventWithMemberPartner crowdfundEvent, CommonInput input, HttpServletRequest request) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> params = CommonInput.appendParams(input);
                eventAsynExportService.endExport(crowdfundEvent, params, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * 众筹结束跟状态改变
     */
    @ResponseBody
    @RequestMapping(value = "update")
    public AjaxResult update(String id, int followState) {
        int i = crowfundFollowUpService.update(id, followState);
        if (i == 1) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("更新异常");
        }
    }

    /**
     * 众筹结束校正数据
     */
    @ResponseBody
    @RequestMapping(value = "revise")
    public AjaxResult revise(String eventId) {
        int i = crowfundFollowUpService.revise(eventId);
        if (i == 1) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("校正异常");
        }
    }


    /**
     * 根据事件查询众筹列表
     *
     * @param projectWithAuthor 查询数据
     * @param page              分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "listForEvent")
    public ModelAndView listForEvent(ProjectWithAuthor projectWithAuthor, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/zcCrowdfundFollowUp");
        page.setLimit(20);
        if(StringUtils.isEmpty(projectWithAuthor.getEventId())){
            return null;
        }
        projectWithAuthor.setDistribution(true);

        ProjectWithAuthor author = new ProjectWithAuthor();
        author.setEventId(projectWithAuthor.getEventId());
        author.setPayType(1);
        List<ProjectForActivityOutput> dpList = projectBizService.projectForActivityList(author, null);

        Integer isSuccess = projectWithAuthor.getIsSuccess();

        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        projectWithAuthor.setPayType(0);//查询普通众筹

        //众筹成功
        if(null != projectWithAuthor.getPayStatus() && "1".equals(projectWithAuthor.getPayStatus())){
            projectWithAuthor.setIsSuccess(1);
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page);

        Integer representNum = distributorRelationService.countForEvent(projectWithAuthor.getEventId());
        projectWithAuthor.setIsSuccess(isSuccess);



        //众筹成功
        if(null != projectWithAuthor.getPayStatus() && "1".equals(projectWithAuthor.getPayStatus())){
            //成功金额
            ProjectAnalyze projectAnalyze = new ProjectAnalyze();
            projectAnalyze.setEventId(projectWithAuthor.getEventId());
            projectAnalyze.setIsSuccess(Constant.IS_CROWFUND_SUCCESS);
            projectAnalyze.setPayType(0);
            Double successfulAmount = projectService.sumProjectOREventAmount(projectAnalyze, 1);
            modelAndView.addObject("successfulAmount", successfulAmount);
        }

        //众筹金额
        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("projectNum", page.getTotalCount());
        modelAndView.addObject("directNum", dpList.size());
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);//回传查询参数
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addAllObjects(orderBizService.getOrderData(projectWithAuthor.getEventId(), 0));


        return modelAndView;
    }


    /**
     * 众筹结束跟进初始化新字段方法
     */
    @ResponseBody
    @RequestMapping(value = "initialization")
    public AjaxResult initialization() {

        List<Event> eventList = crowfundFollowUpService.selectEventList();
        for (Event event : eventList) {
            List<Project> list = crowfundFollowUpService.selectEvent(event.getId());
            for (Project project : list) {
                Project project1 = projectService.get(project.getId());
                project1.setRefundState(project.getRefund());
                projectService.update(project1);
            }
        }
        return AjaxResult.success();
    }
}
